package cn.banacoo.common.dto;

import java.io.Serializable;

import org.springframework.http.HttpStatus;


public class JKResponse<T> implements Serializable {
    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private int code;
    private String error;
    private T data;

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public String getError() {
        return error;
    }

    public void setError(String error) {
        this.error = error;
    }

    @Override
    public String toString() {
        StringBuilder result = new StringBuilder("JKResponse");
        if (data != null)
            result.append("<" + data.getClass().getSimpleName() + ">");
        result.append(": {code=" + code);
        if (data != null)
            result.append(", data=" + data);
        if (error != null)
            result.append(", error=" + error);
        result.append(" }");


        return result.toString();
    }


    /**
     * 调用成功, 无返回对象
     *
     * @param
     * @param <T>
     * @return
     */
    public static <T> JKResponse<T> success() {
        return success(null);
    }

    /**
     * 调用成功, 有返回对象
     *
     * @param
     * @param <T>
     * @return
     */
    public static <T> JKResponse<T> success(T object) {
    	JKResponse<T> response = new JKResponse<T>();
        response.code = HttpStatus.OK.value();
        response.error = "ok";
        response.setData(object);

        return response;
    }

    /**
     * 调用成功, 无返回对象
     *
     * @param
     * @param <T>
     * @return
     */
    public static <T> JKResponse<T> failure(int code, String error) {
        JKResponse<T> response = new JKResponse<T>();
        response.setCode(code);
        response.setError(error);

        return response;
    }
    
    /**
     * 接口调用失败，返回异常信息
     */
    public static <T> JKResponse<T> exception(Exception e) {
        JKResponse<T> result = new JKResponse<T>();
        result.setCode(-1);
        result.setError(e.getMessage());
        return result;
    }
}
